using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Object_CheckPoint : MonoBehaviour,ISaveable
{
    [SerializeField] private string checkPointId;
    [SerializeField] private Transform checkPoint;
    private Animator animator;
    private AudioSource fireAudioSource;
    private bool isActive = false;

#if UNITY_EDITOR
    private void OnValidate()
    {
        if (string.IsNullOrEmpty(checkPointId))
            checkPointId = System.Guid.NewGuid().ToString();
    }
#endif

    private void Awake()
    {
        animator = GetComponentInChildren<Animator>();
        fireAudioSource = GetComponent<AudioSource>();
    }

    public string GetCheckPointId() => checkPointId;
    public Vector3 GetCheckPointPosition() => checkPoint == null ? transform.position : checkPoint.position;


    private void ActiveCheckPointAnim(bool active)
    {
        isActive = active;
        animator.SetBool("CheckPoint", active);
        if (isActive && fireAudioSource.isPlaying == false)
            fireAudioSource.Play();
        if (isActive == false)
            fireAudioSource.Stop();
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {

        if (collision.GetComponent<Player>() != null)
        {
            ActiveCheckPointAnim(true);
            SaveManager.Instance.SaveGame();
        }
    }

    public void SaveData(ref GameData gameData)
    {
        if (isActive == false)
            return;

        if (gameData.checkPoint.ContainsKey(checkPointId) == false)
            gameData.checkPoint[checkPointId] = isActive;
    }

    public void LoadData(GameData gameData)
    {
        bool canActive = gameData.checkPoint.TryGetValue(checkPointId, out canActive);

        ActiveCheckPointAnim(canActive);
    }
}
